package com.yuke.cloud.service.opc.controller.frontend;

import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.opc.dto.FileInfo;
import com.yuke.cloud.service.opc.entity.FastDFSFile;
import com.yuke.cloud.service.opc.service.OpcFileService;
import com.yuke.cloud.service.opc.utils.FastDFSClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Api(value = "WEB - PictureUploadController", tags = "处理图片文件上传相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Slf4j
@RestController
public class PictureController extends BaseController{
    @Resource
    private OpcFileService opcFileService;

    private static final String[] IMAGETYPE = {"bmp", "gif", "jpg", "pic", "png", "tif", "jpeg"};

    @PostMapping("/image/upload/{amount}")
    @ApiOperation(httpMethod = "POST", value = "上传图片")
    public Wrapper<List<String>> fileUpload(@ApiParam(name = "file", value = "上传的图片") @RequestParam("file") MultipartFile file,
                                            @ApiParam(name = "amount", value = "需要上传图片的数量") @PathVariable int amount) {

        log.info("----- Enter '/image/upload/{}' fileUpload() -----", amount);
        List<String> pathList = new ArrayList<>();
        if (file == null) {
            log.info("The incoming file is null");
            return WrapMapper.error("传入文件为空，请重新上传");
        }
        String fileName = file.getOriginalFilename();
        String ext =  fileName.substring(fileName.lastIndexOf(".") + 1);
        InputStream smallInputStream = null;
        try {
            pathList.add(opcFileService.saveFiles(file.getInputStream(), fileName, ext));
            if (amount == 2) {
                smallInputStream = disposeImage(file, 200, 200);
                pathList.add(opcFileService.saveFiles(smallInputStream, fileName, ext));
            }
        } catch (Exception e) {
            log.error("Upload file failed",e);
        }
        log.info("----- Leave '/image/upload/{}' fileUpload() -----", amount);
        return WrapMapper.ok(pathList);
    }

    @PostMapping("/mall/image/upload/{amount}")
    @ApiOperation(httpMethod = "POST", value = "上传图片")
    public Wrapper<List<String>> fileUploadMall(@ApiParam(name = "file", value = "上传的图片") @RequestParam("file") MultipartFile file,
                                            @ApiParam(name = "amount", value = "需要上传图片的数量") @PathVariable int amount) {
        log.info("----- Enter '/mall/image/upload/{}' fileUploadMall() -----", amount);
        List<String> pathList = this.fileUpload(file, amount).getResult();
        log.info("----- Leave '/mall/image/upload/{}' fileUploadMall() -----", amount);
        return WrapMapper.ok(pathList);
    }

//    @DeleteMapping("/image")
    @ApiOperation(httpMethod = "DELETE", value = "删除图片")
    public Wrapper<Boolean> fileDelete(@ApiParam(name = "fileInfo", value = "删除图片") @RequestBody FileInfo fileInfo) {
        log.info("----- Enter '/image/delete' fileDelete() -----");
        int status = -1;
        try {
            log.info("GroupName is : {}, RemoteFileName is : {}", fileInfo.getGroupName(), fileInfo.getRemoteFileName());
            status = FastDFSClient.deleteFile(fileInfo.getGroupName(), fileInfo.getRemoteFileName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("----- Leave '/image/delete' fileDelete(), and status is {} -----", status == -1 ? false : true);
        return WrapMapper.ok(status == -1 ? false : true);
    }

    @DeleteMapping("/image")
    @ApiOperation(httpMethod = "DELETE", value = "删除图片")
    public Wrapper<Boolean> fileDeleteList(@ApiParam(name = "fileInfo", value = "删除图片") @RequestBody FileInfo fileInfo) {
        log.info("----- Enter '/image/delete' fileDelete() -----");
        if (fileInfo == null)
            return WrapMapper.ok(true);
        List<String> fileNameList = Arrays.asList(fileInfo.getFileNames().split(","));
        int status = -1;
        try {
            for (String fileName : fileNameList) {
                if (fileName == null || fileName.equals(""))
                    return WrapMapper.ok(true);
                FileInfo file = new FileInfo();
                List<String> strs = Arrays.asList(fileName.split("/"));
                file.setGroupName(strs.get(3));
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 4; i < strs.size(); i++) {
                    stringBuffer.append(strs.get(i));
                    if (i != strs.size() - 1)
                        stringBuffer.append("/");
                }
                file.setRemoteFileName(stringBuffer.toString());
                log.info("--- groupName is {}, remoteFileName is {} ---", file.getGroupName(), file.getRemoteFileName());
                status = FastDFSClient.deleteFile(file.getGroupName(), file.getRemoteFileName());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("----- Leave '/image/delete' fileDelete(), and status is {} -----", status == -1 ? false : true);
        return WrapMapper.ok(status == -1 ? false : true);
    }

    private synchronized static InputStream disposeImage(MultipartFile file, int new_w, int new_h) {
        log.info("----- Enter disposeImage() -----");
        InputStream inputStream = null;
        String fileName = file.getOriginalFilename();
        BufferedImage srcBufferedImage = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            srcBufferedImage = ImageIO.read(file.getInputStream());
            BufferedImage newBufferedImage = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = newBufferedImage.createGraphics();
            graphics.drawImage(srcBufferedImage, 0, 0, srcBufferedImage.getWidth(), srcBufferedImage.getHeight(), null);
            graphics.dispose();
            newBufferedImage.getGraphics().drawImage(srcBufferedImage.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0, null);
            ImageIO.write(newBufferedImage, fileName.substring(fileName.lastIndexOf(".") + 1), byteArrayOutputStream);
//          multipartFile = new MockMultipartFile(fileName, new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
            inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

        } catch (IOException e) {
            log.error("IO Exception : ", e);
        } finally {
            try {
                inputStream.close();
                byteArrayOutputStream.close();
            } catch (IOException e) {
                log.error("IO Exception : Stream close() fail", e);
            }
        }
        log.info("----- Leave disposeImage() -----");
        return inputStream;
    }

//    public String saveFile(InputStream inputStream, String fileName, String ext) throws IOException {
//        log.info("----- Enter saveFile() -----");
//        String[] fileAbsolutePath={};
//        byte[] file_buff = null;
//        if(inputStream!=null){
//            int len1 = inputStream.available();
//            file_buff = new byte[len1];
//            inputStream.read(file_buff);
//        }
//        inputStream.close();
//        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
//        try {
//            fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
//        } catch (Exception e) {
//            log.error("upload file Exception!",e);
//        }
//        if (fileAbsolutePath==null) {
//            log.error("upload file failed,please upload again!");
//        }
//        String path = fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
//        log.info("----- Leave saveFile()，返回值为-----" + path);
//        return path;
//    }

    /**
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String saveFile(MultipartFile multipartFile) throws IOException {
        log.info("进入saveFile方法");
        String[] fileAbsolutePath={};
        String fileName=multipartFile.getOriginalFilename().equals("") ? multipartFile.getName():multipartFile.getOriginalFilename();
        log.info(fileName);
        log.info("============"+multipartFile.getName()+ "--------------" + (multipartFile.getOriginalFilename().equals("")) + "============");
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream=multipartFile.getInputStream();
        if(inputStream!=null){
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
        try {
            fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
        } catch (Exception e) {
            log.error("upload file Exception!",e);
        }
        if (fileAbsolutePath==null) {
            log.error("upload file failed,please upload again!");
        }
        String path = fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
        log.info("退出saveFile方法，返回值为" + path);
        return path;
    }


}
